package com.fullstack.server

import cats.*
import cats.implicits.*
import cats.effect.*
import com.fullstack.server.config.AppConfig
import com.fullstack.server.http.RouteApi
import com.fullstack.server.modules.{Core, Database}
import org.http4s.ember.server.EmberServerBuilder
import org.http4s.server.{Router, Server}
import org.http4s.server.middleware.*
import org.typelevel.log4cats.Logger
import org.typelevel.log4cats.slf4j.Slf4jLogger
import pureconfig.ConfigSource


object Server extends IOApp.Simple {



//  private val appConfig: IO[AppConfig] = ConfigSource.default.loadF[IO, AppConfig]
  private val appConfig: IO[AppConfig] =
    for
      env <- IO.delay(sys.env.getOrElse("APP_ENV", "dev")) // 通过环境变量选择环境，默认为开发环境, 开发环境设为：prod
      appConfig <- IO.delay(ConfigSource.resources(s"application-$env.conf").loadOrThrow[AppConfig])
      _ <- IO.delay(System.setProperty("logback.configurationFile", s"logback-$env.xml")) // 设置日志输出配置
    yield
      appConfig


  override def run: IO[Unit] =
    appConfig.flatMap {
      case AppConfig(environment, postgresConfig, emberConfig, securityConfig) =>
        given logger: Logger[IO] = Slf4jLogger.getLogger[IO]
        val appResource: Resource[IO, Server] =
          for
            xa <- Database.makePostgresResource[IO](postgresConfig)
            core <- Core[IO](xa)
            routeApi <- RouteApi[IO](core)
            server <- EmberServerBuilder.default[IO]
              .withHost(emberConfig.host)
              .withPort(emberConfig.port)
              .withHttpApp(CORS.policy.withAllowOriginAll(Router("/" -> routeApi.routes)).orNotFound)
              .build
          yield server

        appResource.use(_ => IO.println("Start...") *> IO.println(s"访问Swagger：http:localhost:${emberConfig.port}/docs") *> IO.never)
        
    }

}
